import { login, logout, getInfo } from '@/api/user'
import {
  getToken,
  setToken,
  removeToken,
  getRole,
  setRole,
  removeRole,
  setCode,
  removeCode,
  getCode,
  setAuth,
  removeAuth
} from '@/utils/auth'
import { resetRouter } from '@/router'

const state = {
  token: getToken(),
  code: getCode(),
  name: '',
  avatar: '',
  vip_rule: -1
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_CODE: (state, code) => {
    state.code = code
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_VIP_RULE: (state, rule) => {
    state.vip_rule = rule
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password: password })
        .then(response => {
          const { data } = response
          commit('SET_TOKEN', data.token)
          commit('SET_CODE', data.code)
          commit('SET_AVATAR', data.logo)
          commit('SET_VIP_RULE', data.vip_rule)
          console.log(data.vip_rule)
          localStorage.setItem('vip_rule', data.vip_rule)
          localStorage.setItem('logo', data.logo)
          if (data.agent === 0 && data.auth.length) {
            setAuth(JSON.stringify(data.auth))
          }
          setToken(data.token)
          setCode(data.code)
          setRole(data.agent === 0 ? 'root' : 'agent')
          resolve()
          // logo
          // localStorage.setItem('logo', data.logo)
        })
        .catch(error => {
          reject(error)
        })
    })
  },
  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token)
        .then(response => {
          const { data } = response

          if (!data) {
            reject('Verification failed, please Login again.')
          }

          const { name, avatar } = data
          commit('SET_NAME', name)
          resolve(data)
        })
        .catch(error => {
          reject(error)
        })
    })
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      // logout(state.token)
      //   .then(() => {
      commit('SET_TOKEN', '')
      commit('SET_CODE', '')
      removeToken()
      removeRole()
      removeCode()
      removeAuth()
      resetRouter()
      resolve()
      // })
      // .catch(error => {
      //   reject(error);
      // });
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_CODE', '')
      removeToken()
      removeRole()
      removeCode()
      removeAuth()
      resetRouter()
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
